package com.example.game_app.fragment;

import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.game_app.R;
import com.example.game_app.adapter.MatchListAdapter;
import com.example.game_app.adapter.MenuAdapter;
import com.example.game_app.util.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;

// ndroid系统尝试在Fragment所属的Activity中寻找onClick方法，而实际上该方法是在Fragment中定义的
public class GameMatchViewFragment extends Fragment {
    // 游戏列表视图
    ListView listView;
    // 游戏元素集合
    List<Map<String, String>> matchList = new ArrayList<>();
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public MenuAdapter menuAdapter;
    // 横向日期菜单列表
    RecyclerView recyclerView;
    List<Map<String, String>> menuList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件并返回视图
        return inflater.inflate(R.layout.game_match_view, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 游戏列表
        listView = view.findViewById(R.id.matchLists);
        // 日期滚动列表
        recyclerView = view.findViewById(R.id.recyclerView);
        getMatchList(view);
        getDateList(view);

    }

    // 获取所有比赛详细信息列表
    public void getMatchList(View view) {
        new Thread() {
            @Override
            public void run() {
                Request request = new Request();
                String result = request.get("/matches/list");
                // 将json转为 matchList
                getJsonArray(result, matchList);
            }
        }.start();
    }

    // 获取比赛时间列表
    public void getDateList(View view) {
        new Thread() {
            @Override
            public void run() {
                Request request = new Request();
                String result = request.get("/matches/list");
                getJsonDateArray(result, menuList);
            }
        }.start();

    }

    // 将比赛时间列表转为为map，并进行数据映射到recyclerView
    private void getJsonDateArray(String result,List<Map<String, String>> menuList) {
        try {
            Set<String> dateSet = new TreeSet<>();
            JSONArray jsonArray = new JSONArray(result);
            // 保证每次访问，清空列表，避免冗余添加
            menuList.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String matchTime = jsonObject.getString("matchTime");
                // 只截取日期部分作为菜单列表  2024-01-05 08:00:00
                matchTime = matchTime.substring(5, 10);
                // 比赛时间去重，且从小到大排序
                dateSet.add(matchTime);
            }
            // 将去重后的比赛时间添加到menuList中
            for (String matchTime : dateSet) {
                Map<String, String> matchMap = new HashMap<>();
                matchMap.put("matchTime", matchTime);
                menuList.add(matchMap);
            }
            // 异步执行适配器数据映射
            mHandler.post(() -> {
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
                // 声明 menuAdapter，便于外界调用menuAdapter的resetSelectPosition()
                menuAdapter = new MenuAdapter(getContext(), listView, menuList);
                recyclerView.setAdapter(menuAdapter);
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    // 将比赛信息转为map，并映射到ListView上
    public void getJsonArray(String data, List<Map<String, String>> matchList) {
        try {
            JSONArray jsonArray = new JSONArray(data);
            // 保证每次访问，情况列表，避免冗余添加
            matchList.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String matchId = String.valueOf(jsonObject.getInt("matchId"));
                String playerA = jsonObject.getString("playerA");
                String playerB = jsonObject.getString("playerB");
                String matchTime = jsonObject.getString("matchTime");
                String score = jsonObject.getString("score");
                String matchDescription = jsonObject.getString("matchDescription");

                Map<String, String> matchMap = new HashMap<>();
                matchMap.put("matchId", matchId);
                matchMap.put("playerA", playerA);
                matchMap.put("playerB", playerB);
                // 只截取 精确时间作为比赛时间
                matchMap.put("matchTime", matchTime.substring(11, 16));
                matchMap.put("score", score);
                matchMap.put("matchDescription", matchDescription);
                matchList.add(matchMap);
            }
            // 将数据映射到游戏列表
            mHandler.post(() -> listView.setAdapter(new MatchListAdapter(requireContext(), matchList, map -> {
                // 创建弹出框 队伍 比分 时间 描述
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(listView.getContext());
                TextView messageView = new TextView(listView.getContext());
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    messageView.setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1);
                    messageView.setGravity(Gravity.CENTER_HORIZONTAL);
                }
                String message = "队伍1：" + map.get("playerA") + "\n" +
                        "队伍2：" + map.get("playerB") + "\n" +
                        "比分：" + map.get("score") + "\n" +
                        "比赛时间：" + map.get("matchTime") + "\n" +
                        "比赛介绍：" + map.get("matchDescription");
                messageView.setText(message);
                alertDialogBuilder.setView(messageView)
                        .setTitle("比赛详情")
                        .setPositiveButton("确定", null)
                        .create()
                        .show();
            })));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }


}
